// 全局懒加载图片队列
window._lazyImages = global._lazyImages = [];

function getParents(elem, parentSelector) {
  if (parentSelector === undefined) {
    return [];
  }
  let parents = [];
  while ((elem = elem['parentNode']) && elem.nodeType !== 9) {
    if (elem.nodeType === 1) {
      if (!elem['parentNode']) {
        break;
      }
      if (elem.className.indexOf(parentSelector) !== -1) {
        parents.push(elem);
      }
    }
  }

  return parents;
}

function debounce(method, delay) {
  let timer = null;
  return function() {
    let self = this,
      args = arguments;
    timer && clearTimeout(timer);
    timer = setTimeout(function() {
      method.apply(self, args);
    }, delay);
  }
}

/**
 * 函数节流方法
 * @param Function fn 延时调用函数
 * @param Number delay 延迟多长时间
 * @return Function 延迟执行的方法
 */
function throttle(fn, delay) {
  var timer = null;
  var previous = null;
  return function() {
    var now = +new Date();
    if (!previous) previous = now;
    var editors = arguments;

    if (now - previous > delay) {
      fn.apply(null, editors);
      previous = now;
      clearTimeout(timer);
    } else {
      clearTimeout(timer);
      timer = setTimeout(function() {
        fn.apply(null, editors);
      }, delay);
    }

  }
};

// 防抖动滚动监听
const debounceScroll = debounce(function() {
  for (let i = 0; i < _lazyImages.length; i++) {
    throttle(function() {
      _lazyImages[i].isInViewport();
    }, 30)()
  }
}, 60);

window.addEventListener('scroll', debounceScroll, true);

const CustomDirective = {
  imageViewPort: {
    inserted(el, binding) {
      let lazyId = Math.round(Math.random()*999999);
      el.setAttribute('lazyId', lazyId);
      binding.lazyImage = true;
      binding.isInViewport = function() {
        let viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        let top = el.clientTop;
        if (top <= viewPortHeight && binding.lazyImage) {
          // console.info(el.getAttribute('lazyId'));
          if (binding.value) {
            if (!binding.value.params) binding.value.params=[]
          }
          binding.value.fun&&binding.value.fun(...binding.value.params);
          binding.lazyImage = false;
        }
      };
      _lazyImages.push({
        lazyId,
        isInViewport: binding.isInViewport
      });
      binding.isInViewport();
    },
    unbind(el, binding) {
      let lazyId =el.getAttribute('lazyId');
      for (let i = _lazyImages.length - 1; i >= 0; i--) {
        if (_lazyImages[i].lazyId === lazyId) {
          console.info(1)
          _lazyImages.splice(i, 1);
        }
      }
    }
  },
  androidAction: {
    bind(el, binding) {
      try {
        el.addEventListener('keydown', function(event) {

          if (event.keyCode === 13 || event.which === 13) {
            event.returnValue = false
            binding.value()
          }
        });
      } catch (e) {
        console.log(e)
      }
    },
    update(el, binding) {
      try {
        el.addEventListener('keydown', function(event) {

          if (event.keyCode === 13 || event.which === 13) {
            event.returnValue = false
            binding.value()
          }
        });
      } catch (e) {
        console.log(e)
      }
    }
  },
  filterSpecialChar: {
    update(el, { value, modifiers }, vnode) {
      try {
        el.addEventListener('keydown', function(event) {

          if (event.keyCode == 32 || event.which == 32) {
            event.returnValue = false
          }
        });
      } catch (e) {
        console.log(e)
      }
    }
  },
  d3Scroll: {
    bind(el, binding) {
      try {
        binding.value(el);
      } catch (e) {
        console.log(e)
      }
    }
  },
  elScroll: {
    update(el, binding) {
      try {
        let fixed = el.querySelector('.el-table__fixed-right');
        if (fixed) {
          binding.value(fixed)
        }

        // elTable.addEventListener('scroll', function(event) {
        //
        //   let $th = $(el).find('.custom-head-column');
        //   console.info(binding.value(fixed, $th));
        // });
      } catch (e) {
        console.log(e)
      }
    }
  },
  customIcon: {
    bind(el, { value, modifiers }, vnode) {
      // ImageToBase64.getBase64(value).then((base) => {
      //   el.style.backgroundImage='url('+base+')';
      // })
      el.style.backgroundImage = 'url(' + value + ')';
    },
    inserted(el, { value, modifiers }, vnode) {
      let isSelect = getParents(el, 'is-selected');
      if (isSelect.length != 0) {
        el.style.backgroundImage = 'url(' + value + ')';
      }
    },
    update(el, { value, modifiers }, vnode) {
      let isSelect = getParents(el, 'is-selected');
      if (isSelect.length != 0) {
        el.style.backgroundImage = 'url(' + value + ')';
      }
    }
  },
  draggable: {
    bind(el) {
      let startPosition = { x: 0, y: 0 };
      let dialogPosition = { x: 0, y: 0 };
      let dragging = false;

      el.handleMouseDown = (e) => {
        // e.stopPropagation();
        // e.preventDefault();
        startPosition.x = e.clientX;
        startPosition.y = e.clientY;
        let rect =  el.getBoundingClientRect()
        dialogPosition.x = parseInt(rect.left, 10) || 0;
        dialogPosition.y = parseInt(rect.top, 10) || 0;

        document.addEventListener('mousemove', handleMouseMove);
        document.addEventListener('mouseup', handleMouseUp);

        dragging = true;


      };

      const handleMouseMove = (e) => {
        if (dragging) {
          const x = dialogPosition.x+e.clientX - startPosition.x;
          const y = dialogPosition.y+e.clientY - startPosition.y;
          el.style.left = `${x}px`;
          el.style.top = `${y}px`;
          el.style.transform= 'none';
        }
      };

      const handleMouseUp = () => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);

        dragging = false;
      };

      el.addEventListener('mousedown', el.handleMouseDown);
      document.addEventListener('mouseup', function(e) {
        if (e.clientY > window.innerWidth || e.clientY<0 || e.clientX<0 ||e.clientX>window.innerHeight) {
          // 在这加入你想执行的代码，此条件下鼠标已经在浏览器外
          el.removeEventListener('mousemove', handleMouseMove);
          el.removeEventListener('mouseup', handleMouseUp);
        }
      });
    },
    unbind(el) {
      console.info(el.handleMouseDown)
      el.addEventListener('mousedown', el.handleMouseDown);
    }
  }
}

CustomDirective.install = function(Vue) {
  Object.keys(CustomDirective).forEach(key => {
    Vue.directive(key, CustomDirective[key])
  });
}

export default CustomDirective;
